<template>
  <el-container>
    <el-header>
      <el-select v-model="searchDate.categoryId" placeholder="请选择部门">
        <template v-for="(item,index) in selectList.categoryList" >
          <el-option
              :key="index"
              :label="item.categoryName"
              :value="item.id">
          </el-option>
        </template>
      </el-select>
      <el-select v-model="searchDate.typeId" placeholder="请选择密级">
        <template v-for="(item,index) in selectList.typeId">
          <el-option
              :key="index"
              :label="item.typeName"
              :value="item.id">
          </el-option>
        </template>
      </el-select>
      <el-select v-model="searchDate.level" placeholder="请选择紧急程度">
        <template v-for="(item,index) in selectList.levelList">
          <el-option
              :key="index"
              :label="item.level"
              :value="item.level">
          </el-option>
        </template>
      </el-select>
      <el-button @click="init">搜索</el-button>
      <DialogOne @update="receive"
                 :selectList="selectList"
                 :tableHeadData="tableHeadData" :tableData="tableData" :dataStandard="dataStandard" :rules="rules"></DialogOne>
      <Dialog2One @update="receive"
                  :selectList="selectList"
                  :tableHeadData="tableHeadData" :tableData="tableData" :dataStandard="dataStandard" :rules="rules"></Dialog2One>

    </el-header>
    <editCOM @edit="editConfirm" @dialogEdit="dialogEditClose" :dialogEditVisible="dialogEditVisible" :tableHeadData="tableHeadData"
             :selectList="selectList" :dataUpdate="dataUpdate" :rules="rules"></editCOM>
    <tableCOM ref="table" @deleteSelectionA="deleteSelection" @handleSizeChangeA="handleSizeChange" @handleCurrentChangeA="handleCurrentChange"
              @handleSelectionChangeA="handleSelectionChange"
              :operator="operator"
              @toggleSelectionA="toggleSelection" :tableHeadData="tableHeadData" :tableData="tableData" :page="page" :pageSize="pageSize" :counts="counts"></tableCOM>
    <edit2COM @edit="editConfirm" @dialogEdit="dialogEditClose" :dialogEditVisible="dialogEdit2Visible" :tableHeadData="tableHeadData"
             :selectList="selectList" :dataUpdate="dataUpdate" :rules="rules"></edit2COM>
    <el-dialog :visible.sync="isSort">
      <el-select v-model="userId" placeholder="请选发送用户">
        <template v-for="(item,index) in selectList.userId">
          <el-option
              :key="index"
              :label="item.realName"
              :value="item.id">
          </el-option>
        </template>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isSort = false">取 消</el-button>
        <el-button type="primary" @click="sendConfirm()">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import DialogOne from "@/components/DialogOne";
import Dialog2One from "@/components/Dialog2One";
import edit2COM from "@/components/edit2COM";

import {
  apiFileAdd,
  apiFileDel,
  apiFileDownload,
  apiFileList,
  apiFileListAll,
  apiFileUpdate, download, downloadExist
} from "@/assets/api/FileAPI";
import searchCOM from "@/components/searchCOM";
import editCOM from "@/components/editCOM";
import tableCOM from "@/components/tableCOM";
import {apiCategoryListAll} from "@/assets/api/CategoryAPI";
import {apiFileTypeListAll} from "@/assets/api/FileTypeAPI";
import state from "@/store/state";
import {apiFileCategoryListAll} from "@/assets/api/FileCategoryAPI";
import {apiUserListAll} from "@/assets/api/UserAPI";
import {apiFileSendAdd} from "@/assets/api/FileSendAPI";
export default {
  components: {tableCOM, editCOM, searchCOM, DialogOne,Dialog2One,edit2COM},
  data(){
    return{
      tableHeadData: [
        {label: '标题', width: '', prop: `title`},
        {label: '内容', width: '', prop: `remark`,table: true,addForm2:true,type:"text"},
        {label: '文件', width: '', prop: `url`,type:"file",table:true},
        {label: '上传日期', width: '', prop: `inputDate`,type:"time",form: true},
        {label: '上传人', width: '', prop: `fromUser`,table: true,form: true},
        {label: '上传人', width: '', prop: `userName`,form: true},
        {label: '密级', width: '', prop: `typeId`,table: true,type: "select"},
        {label: '密级', width: '', prop: `typeName`,form: true},
        {label: '紧急程度', width: '', prop: `level`},
      ],
      userId:'',
      dataStandard :{
        title:'',
        remark:'',
        url:'',
        inputDate:'',
        fromUser:'',
        toUser:'',
        status:'',
        typeId:'',
        level:''
      },
      searchDate:[],
      rules:{
        title: [{required: true, message: '标题不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
        remark: [{required: true, message: '备注不可为空', trigger: 'blur'}],
        url: [{required: true, message: 'url不可为空', trigger: 'blur'}],
        inputDate: [{required: true, message: '存入日期不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
        fromUser: [{required: true, message: '发件人不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
        toUser: [{required: true, message: '收件人不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
        status: [{required: true, message: '状态不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
        level: [{required: true, message: '紧急程度不可为空', trigger: 'blur'},{pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号'}],
      },
      selectList:{
        categoryList:[],
        typeList:[],
        levelList:[]
      },
      dataUpdate :{},
      pageSize: 10,
      counts:0,
      page:1,
      searchName:'',
      branch:false,
      dialogEditVisible:false,
      multipleSelection:[],
      deleteID:[],
      tableData:[],
      sendData:'',
      isSort:false,
      dialogEdit2Visible:false,
      operator:[
        {'text':'编辑', click: (row, col, cellValue) => {return this.edit(row)},
          isShow: (row, $index) => {
            const newInfo = state.userInfo.replace(/\"/g, "");
            if(row.userName === newInfo){
              return false;
            }
            return true;
          }
        },
        {'text':'发送', click: (row, col, cellValue) => {return this.send(row)},
          isShow: (row, $index) => {
            const newInfo = state.userInfo.replace(/\"/g, "");
            if(row.userName === newInfo){
              return false;
            }
            return true;
          }
        },
        {'text':'下载', click: (row, col, cellValue) => {return this.download(row)},
          isShow: (row, $index) => {
            if(row.status != '0'){
              return false;
            }
            return true;
          }},
        {'text':'删除', click: (row, col, cellValue) => {return this.del(row.id)},
          isShow: (row, $index) => {
            const newInfo = state.userInfo.replace(/\"/g, "");
            if(row.userName === newInfo){
              return false;
            }
            return true;
          }
        },
      ],

    }
  },
  created() {
    this.initList()
    this.init()
  },
  methods: {
    parentSubmit(){
      apiFileAdd(this.dataUpdate)
      this.init()
    },
    receive(var1){
      this.dataUpdate = var1;
      this.parentSubmit()
    },
    initList(){
      apiUserListAll().then(res =>{
        this.selectList.userId = res.data.data
      })
    },
    sendConfirm(){
      const p = {
        toUser:this.userId,
        file:this.sendDate.id
      }
      apiFileSendAdd(p).then(resp => {
        if(resp.data.code === 1){
          this.$message.success("成功")
          this.isSort = false
        }else {
          this.$message.error(resp.data.msg)
        }
        this.init()
      })
    },
    async init () {
      const params = {
        page: this.page,
        pageSize: this.pageSize,
        name: this.searchName ? this.searchName : undefined,
        categoryId: this.searchDate.categoryId ? this.searchDate.categoryId : undefined,
        typeId: this.searchDate.typeId ? this.searchDate.typeId : undefined,
        level: this.searchDate.level ? this.searchDate.level : undefined
      }

      apiFileListAll().then(res =>{
        const list = res.data.data

        this.selectList.levelList = list
      })
      apiCategoryListAll().then(res =>{
        const list = res.data.data
        for (let i = 0; i<list.length; i ++){
          list[i].name = list[i].categoryName
        }
        this.selectList.categoryList = list
      })
      apiFileTypeListAll().then(res =>{
        const list = res.data.data
        for (let i = 0; i<list.length; i ++){
          list[i].name = list[i].typeName
        }
        this.selectList.typeId = list
      })


      apiFileList(params).then(resp => {
        this.tableData = resp.data.data.records,
            this.counts = resp.data.data.total
      })

    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.table.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.table.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      let checkArr = []
      val.forEach((n) => {
        checkArr.push(n.id)
      })
      this.multipleSelection = checkArr;
    },
    deleteSelection(){
      this.branch = true
      this.del()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.init()
    },
    handleCurrentChange(val) {
      this.page = val
      this.init()
    },
    del(rowId){
      this.deleteID = this.branch ? this.multipleSelection : rowId
      if (this.deleteID.length === 0 && this.branch) {
        return this.$message.error('请选择删除对象')
      }
      this.$confirm('确认删除, 是否继续?', '确定删除', {
        'confirmButtonText': '确定',
        'cancelButtonText': '取消',
      }).then(() => {
        console.log(this.branch)
        apiFileDel(this.branch ? this.deleteID.join(",") : this.deleteID).then(resp =>{
          if (resp.data.code === 1){
            this.$message.success("成功")
          }
        })
        this.branch = false
        this.init()
      })
    },
    edit(row){
      this.dialogEditVisible = true
      this.dataUpdate = JSON.parse(JSON.stringify(row))
    },
    dialogEditClose(){
      this.dialogEditVisible = false
    },

    send(row){
      this.sendDate = row
      this.isSort = true
      console.log(isSort)
    },
    editConfirm(data){
      apiFileUpdate(data).then(resp => {
        if(resp.data.code === 1){
          this.$message.success("成功")
        }else {
          this.$message.error(resp.data.msg)
        }
        this.init()
      })
      this.dialogEditVisible = false
    },

    download(row){
      const p ={
        name:row.url,
        id:row.id,
        typeId:row.typeId
      }


      if (row.url === '' || row.url===null){
        downloadExist(p).then(res =>{
          if (res.data.size == 0) {
            return this.$message.error("权限不足");
          }
          if (state.userInfo == null){
            return;
          }
          var name = row.title + ".pdf";
          let blob = new Blob([res.data], {
            type: "application/vnd.ms-excel;charset=utf-8",
          });
          var url = window.URL.createObjectURL(blob);
          var aLink = document.createElement("a"); //创建a标签
          aLink.style.display = "none";
          aLink.href = url;
          aLink.setAttribute("download", name); // 设置文件 name
          document.body.appendChild(aLink);
          aLink.click(); //自执行下载
          document.body.removeChild(aLink); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }).catch((error) => {});
        return
      }

      download(p).then(res =>{
        console.log(res);
        if (res.data.size == 0) {
          return this.$message.error("权限不足");
        }
        if (state.userInfo == null){
          return;
        }
        var name = row.title + ".pdf";
        let blob = new Blob([res.data], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });
        var url = window.URL.createObjectURL(blob);
        var aLink = document.createElement("a"); //创建a标签
        aLink.style.display = "none";
        aLink.href = url;
        aLink.setAttribute("download", name); // 设置文件 name
        document.body.appendChild(aLink);
        aLink.click(); //自执行下载
        document.body.removeChild(aLink); //下载完成移除元素
        window.URL.revokeObjectURL(url); //释放掉blob对象
      }).catch((error) => {});
    },

  },
}
</script>
<style scoped>
</style>